
Shader "UI/Custom/CrystallineEdgeEffect"
{
    Properties
    {
        [PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
        _Color ("Tint", Color) = (1,1,1,1)

        _Progress ("Progress", Range(0, 1)) = 0.5
        _EdgeWidth ("Edge Width", Range(0, 0.5)) = 0.1
        _CrystallineIntensity ("Crystalline Intensity", Range(0, 1)) = 0.5
        _CrystallineScale ("Crystalline Scale", Range(1, 100)) = 20
        _CrystallineSpeed ("Crystalline Speed", Range(0, 10)) = 1

        _StencilComp ("Stencil Comparison", Float) = 8
        _Stencil ("Stencil ID", Float) = 0
        _StencilOp ("Stencil Operation", Float) = 0
        _StencilWriteMask ("Stencil Write Mask", Float) = 255
        _StencilReadMask ("Stencil Read Mask", Float) = 255

        _ColorMask ("Color Mask", Float) = 15

        [Toggle(UNITY_UI_ALPHACLIP)] _UseUIAlphaClip ("Use Alpha Clip", Float) = 0
    }

    SubShader
    {
        Tags
        {
            "Queue"="Transparent"
            "IgnoreProjector"="True"
            "RenderType"="Transparent"
            "PreviewType"="Plane"
            "CanUseSpriteAtlas"="True"
        }

        Stencil
        {
            Ref [_Stencil]
            Comp [_StencilComp]
            Pass [_StencilOp]
            ReadMask [_StencilReadMask]
            WriteMask [_StencilWriteMask]
        }

        Cull Off
        Lighting Off
        ZWrite Off
        ZTest [unity_GUIZTestMode]
        Blend SrcAlpha OneMinusSrcAlpha
        ColorMask [_ColorMask]

        Pass
        {
            Name "Default"
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma target 2.0

            #include "UnityCG.cginc"
            #include "UnityUI.cginc"

            #pragma multi_compile_local _ UNITY_UI_CLIP_RECT
            #pragma multi_compile_local _ UNITY_UI_ALPHACLIP

            struct appdata_t
            {
                float4 vertex : POSITION;
                float4 color : COLOR;
                float2 texcoord : TEXCOORD0;
                UNITY_VERTEX_INPUT_INSTANCE_ID
            };

            struct v2f
            {
                float4 vertex : SV_POSITION;
                fixed4 color : COLOR;
                float2 texcoord : TEXCOORD0;
                float4 worldPosition : TEXCOORD1;
                UNITY_VERTEX_OUTPUT_STEREO
            };

            sampler2D _MainTex;
            fixed4 _Color;
            fixed4 _TextureSampleAdd;
            float4 _ClipRect;
            float4 _MainTex_ST;

            // 自定义属性
            uniform float _Progress;
            uniform float _EdgeWidth;
            uniform float _CrystallineIntensity;
            uniform float _CrystallineScale;
            uniform float _CrystallineSpeed;

            v2f vert(appdata_t v)
            {
                v2f OUT;
                UNITY_SETUP_INSTANCE_ID(v);
                UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(OUT);
                OUT.worldPosition = v.vertex;
                OUT.vertex = UnityObjectToClipPos(OUT.worldPosition);

                OUT.texcoord = TRANSFORM_TEX(v.texcoord, _MainTex);

                OUT.color = v.color * _Color;
                return OUT;
            }

            // 生成噪声值的函数
            float random(float2 st)
            {
                return frac(sin(dot(st.xy, float2(12.9898, 78.233))) * 43758.5453123);
            }

            // 晶格化效果函数
            float2 crystallineEffect(float2 uv, float progress, float edgeWidth, float intensity, float scale, float speed)
            {
                // 计算显示区域（从下往上）
                float showMask = step(uv.y, progress);

                // 计算边缘区域
                float edgeStart = max(0, progress - edgeWidth);
                float inEdgeArea = step(edgeStart, uv.y) * step(uv.y, progress);

                // 只在边缘区域且仍在动画过程中应用晶格化
                float applyCrystalline = inEdgeArea * showMask;

                if (applyCrystalline < 0.001)
                {
                    return uv; // 不在边缘区域或已完成动画，不应用晶格化
                }

                // 在边缘区域内创建渐变效果
                float edgeProgress = 1.0 - saturate((progress - uv.y) / edgeWidth);

                // 添加渐变消失效果，避免晶格化突然消失
                float fadeOutFactor = saturate((1.0 - progress) / edgeWidth);
                
                // 将UV坐标缩放
                float2 scaledUV = uv * scale;

                // 创建晶格单元坐标
                float2 cell = floor(scaledUV);

                // 为每个晶格单元生成随机值
                float cellRandom = random(cell);

                // 基于时间的动画效果
                float timeOffset = _Time.y * speed;

                // 计算晶格化偏移，结合边缘渐变和整体渐变消失
                float2 offset = float2(
                    sin(cellRandom * 10.0 + timeOffset),
                    cos(cellRandom * 10.0 + timeOffset)
                ) * intensity * 0.1 * applyCrystalline * edgeProgress * fadeOutFactor;

                // 应用偏移到纹理坐标
                float2 newUV = uv + offset;

                return newUV;
            }


            fixed4 frag(v2f IN) : SV_Target
            {
                // 获取原始纹理坐标
                float2 uv = IN.texcoord;

                // 应用晶格化效果（仅边缘区域）
                float2 crystUV = crystallineEffect(
                    uv,
                    _Progress,
                    _EdgeWidth,
                    _CrystallineIntensity,
                    _CrystallineScale,
                    _CrystallineSpeed
                );

                // 采样纹理
                half4 color = (tex2D(_MainTex, crystUV) + _TextureSampleAdd) * IN.color;

                // 应用从下往上的显示效果
                float showMask = step(uv.y, _Progress);
                color.a *= showMask;

                #ifdef UNITY_UI_CLIP_RECT
                color.a *= UnityGet2DClipping(IN.worldPosition.xy, _ClipRect);
                #endif

                #ifdef UNITY_UI_ALPHACLIP
                clip(color.a - 0.001);
                #endif

                return color;
            }
            ENDCG
        }
    }
}